#include "stdafx.h"
#include "ConsoleLogListener.h"

namespace Cvekas {

ConsoleLogListener::ConsoleLogListener()
{
	::AllocConsole();
	h_stdout = ::GetStdHandle(STD_OUTPUT_HANDLE);
}

void ConsoleLogListener::add()
{
	// If user closes this console window lots of memory will be leaked.
	const std::string message = "Don't close this console window, close main window instead\n";

	// If we pass NULL as 4-th argument to WriteConsole access violation exception will be thrown.
	DWORD tmp;
	::WriteConsole(h_stdout, message.c_str(), static_cast<DWORD>(message.size()), &tmp, NULL);
}

void ConsoleLogListener::remove()
{
	::FreeConsole();
}

void ConsoleLogListener::sendMsg(const std::string& msg)
{
	// If we pass NULL as 4-th argument to WriteConsole access violation exception will be thrown.
	DWORD tmp;
	::WriteConsole(h_stdout, msg.c_str(), static_cast<DWORD>(msg.size()), &tmp, NULL);
	::WriteConsole(h_stdout, "\n", 1, &tmp, NULL);
}

} // namespace
